package com.hl.ruoyilkshop.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hl.ruoyilkshop.mapper.BusinessClassMapper;
import com.hl.ruoyilkshop.domain.BusinessClass;
import com.hl.ruoyilkshop.service.IBusinessClassService;
import java.util.HashSet;
import java.util.Set;

/**
 * 店铺分类Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-07
 */
@Service
public class BusinessClassServiceImpl implements IBusinessClassService 
{
    @Autowired
    private BusinessClassMapper businessClassMapper;

    /**
     * 查询店铺分类
     * 
     * @param id 店铺分类主键
     * @return 店铺分类
     */
    @Override
    public BusinessClass selectBusinessClassById(Long id)
    {
        return businessClassMapper.selectBusinessClassById(id);
    }

    /**
     * 查询店铺分类列表
     * 
     * @param businessClass 店铺分类
     * @return 店铺分类
     */
    @Override
    public List<BusinessClass> selectBusinessClassList(BusinessClass businessClass)
    {
        return businessClassMapper.selectBusinessClassList(businessClass);
    }

    /**
     * 查询店铺分类层级列表（树形结构）
     */
    @Override
    public List<BusinessClass> selectBusinessClassTreeList(BusinessClass businessClass)
    {
        // 获取所有分类数据
        List<BusinessClass> allClasses = businessClassMapper.selectBusinessClassTreeList(businessClass);
        
        // 如果有搜索条件，需要处理搜索结果
        if (businessClass != null && (businessClass.getName() != null && !businessClass.getName().isEmpty() || 
            businessClass.getBusinessId() != null || businessClass.getLevel() != null || 
            businessClass.getGoodsType() != null)) {
            return buildSearchResultTree(allClasses, businessClass);
        }
        
        // 构建树形结构
        return buildTreeList(allClasses);
    }

    /**
     * 构建树形结构
     * 
     * @param allClasses 所有分类数据
     * @return 树形结构的分类列表
     */
    private List<BusinessClass> buildTreeList(List<BusinessClass> allClasses)
    {
        List<BusinessClass> treeList = new ArrayList<>();
        
        // 获取所有一级分类（parentId为null或0的）
        List<BusinessClass> rootClasses = allClasses.stream()
                .filter(cls -> cls.getParentId() == null || cls.getParentId() == 0)
                .collect(Collectors.toList());
        
        // 递归构建树形结构
        for (BusinessClass rootClass : rootClasses) {
            rootClass.setChildren(getChildren(rootClass.getId(), allClasses));
            treeList.add(rootClass);
        }
        
        return treeList;
    }

    /**
     * 递归获取子分类
     * 
     * @param parentId 父分类ID
     * @param allClasses 所有分类数据
     * @return 子分类列表
     */
    private List<BusinessClass> getChildren(Long parentId, List<BusinessClass> allClasses)
    {
        List<BusinessClass> children = new ArrayList<>();
        
        for (BusinessClass cls : allClasses) {
            if (parentId.equals(cls.getParentId())) {
                cls.setChildren(getChildren(cls.getId(), allClasses));
                children.add(cls);
            }
        }
        
        return children;
    }

    /**
     * 构建搜索结果树形结构
     */
    private List<BusinessClass> buildSearchResultTree(List<BusinessClass> searchResults, BusinessClass searchCriteria)
    {
        if (searchResults.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取所有分类数据用于构建完整树形结构
        List<BusinessClass> allClasses = businessClassMapper.selectBusinessClassTreeList(new BusinessClass());
        
        // 收集所有需要显示的分类ID（包括父分类和子分类）
        Set<Long> categoryIdsToShow = new HashSet<>();
        
        for (BusinessClass result : searchResults) {
            // 添加搜索结果本身
            categoryIdsToShow.add(result.getId());
            
            // 如果是子分类，添加其所有父分类
            addParentCategories(result.getId(), allClasses, categoryIdsToShow);
            
            // 如果是父分类，添加其所有子分类
            addChildCategories(result.getId(), allClasses, categoryIdsToShow);
        }
        
        // 构建包含完整层级关系的树形结构
        return buildTreeListWithFilter(allClasses, categoryIdsToShow);
    }

    /**
     * 递归添加父分类
     */
    private void addParentCategories(Long categoryId, List<BusinessClass> allClasses, Set<Long> categoryIdsToShow)
    {
        BusinessClass category = allClasses.stream()
                .filter(c -> c.getId().equals(categoryId))
                .findFirst()
                .orElse(null);
        
        if (category != null && category.getParentId() != null && category.getParentId() != 0) {
            categoryIdsToShow.add(category.getParentId());
            addParentCategories(category.getParentId(), allClasses, categoryIdsToShow);
        }
    }

    /**
     * 递归添加子分类
     */
    private void addChildCategories(Long categoryId, List<BusinessClass> allClasses, Set<Long> categoryIdsToShow)
    {
        for (BusinessClass category : allClasses) {
            if (categoryId.equals(category.getParentId())) {
                categoryIdsToShow.add(category.getId());
                addChildCategories(category.getId(), allClasses, categoryIdsToShow);
            }
        }
    }

    /**
     * 根据过滤条件构建树形结构
     */
    private List<BusinessClass> buildTreeListWithFilter(List<BusinessClass> allClasses, Set<Long> categoryIdsToShow)
    {
        List<BusinessClass> treeList = new ArrayList<>();
        
        // 获取所有一级分类（parentId为null或0的）
        List<BusinessClass> rootClasses = allClasses.stream()
                .filter(cls -> (cls.getParentId() == null || cls.getParentId() == 0) && 
                               categoryIdsToShow.contains(cls.getId()))
                .collect(Collectors.toList());
        
        // 递归构建树形结构
        for (BusinessClass rootClass : rootClasses) {
            rootClass.setChildren(getChildrenWithFilter(rootClass.getId(), allClasses, categoryIdsToShow));
            treeList.add(rootClass);
        }
        
        return treeList;
    }

    /**
     * 递归获取子分类（带过滤）
     */
    private List<BusinessClass> getChildrenWithFilter(Long parentId, List<BusinessClass> allClasses, Set<Long> categoryIdsToShow)
    {
        List<BusinessClass> children = new ArrayList<>();
        
        for (BusinessClass cls : allClasses) {
            if (parentId.equals(cls.getParentId()) && categoryIdsToShow.contains(cls.getId())) {
                cls.setChildren(getChildrenWithFilter(cls.getId(), allClasses, categoryIdsToShow));
                children.add(cls);
            }
        }
        
        return children;
    }

    /**
     * 新增店铺分类
     * 
     * @param businessClass 店铺分类
     * @return 结果
     */
    @Override
    public int insertBusinessClass(BusinessClass businessClass)
    {
        return businessClassMapper.insertBusinessClass(businessClass);
    }

    /**
     * 修改店铺分类
     * 
     * @param businessClass 店铺分类
     * @return 结果
     */
    @Override
    public int updateBusinessClass(BusinessClass businessClass)
    {
        return businessClassMapper.updateBusinessClass(businessClass);
    }

    /**
     * 批量删除店铺分类
     * 
     * @param ids 需要删除的店铺分类主键
     * @return 结果
     */
    @Override
    public int deleteBusinessClassByIds(Long[] ids)
    {
        return businessClassMapper.deleteBusinessClassByIds(ids);
    }

    /**
     * 删除店铺分类信息
     * 
     * @param id 店铺分类主键
     * @return 结果
     */
    @Override
    public int deleteBusinessClassById(Long id)
    {
        return businessClassMapper.deleteBusinessClassById(id);
    }
}
